// UserConfig.jsx
import React, {useState, useEffect} from 'react';
import {Form, Input, Button, Spin, Alert, message, Row, Col, Space, Select, DatePicker, Typography, Modal} from 'antd';
import {request} from "../utils/requset";
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import dayjs from 'dayjs'; // 导入 dayjs 用于日期处理
import {useDispatch} from "react-redux";
import {setSysConfig} from "../store/modules/pzStore";

const {Option} = Select;
const {Title} = Typography;
const UserConfig = () => {
    const [form] = Form.useForm();
    const [typeList, setTypeList] = useState([]); // 可选项
    const [initialSelected, setInitialSelected] = useState([]); // 初始值
    const [modelist, setModelist] = useState([]);
    const [databaselist, setDatabaselist] = useState([]);
    const [databasetype, setDatabasetype] = useState(null);
    const [loading, setLoading] = useState(false); // 获取配置时的加载状态
    const [saving, setSaving] = useState(false);   // 保存配置时的加载状态
    const [error, setError] = useState(null);      // 错误信息
    const [config, setConfig] = useState({});    // 当前配置
    // const sysConfig = useSelector(state => state.pz.sysConfig)
    const dispatch = useDispatch();

    // 获取当前用户配置
    const fetchUserConfig = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await request.get('/rpa/config');
            const data = response.data;

            // 解析 modelist
            const login_way_list = data.login_way_list.split(',').map((login_way) => login_way.trim());
            setModelist(login_way_list);
            setConfig(data);
            setTypeList(data.qzq_type_list.split(","));
            setInitialSelected(data.qzq_type.split(","));
            setDatabaselist(data.databasetypelist.split(","))
            setDatabasetype(data.databasetype)
            // 填充表单
            form.setFieldsValue({
                dwbh: data.dwbh,
                dwid: data.dwid,
                dwmc: data.dwmc,
                ledger: data.ledger,
                zbbh: data.zbbh,
                kmtx: data.kmtx,
                kmtx_id: data.kmtx_id,
                kjnd: data.kjnd ? dayjs(data.kjnd) : null,
                model: data.model,
                selectedItems: data.qzq_type.split(","),
                login_way: data.login_way,
                smw_net: data.smw_net,
                nw_net: data.nw_net,
                gscloud_username: data.gscloud_username,
                gscloud_password: data.gscloud_password,
                need_report_desc: data.need_report_desc,
            });
            // 保存配置到store
            dispatch(setSysConfig(data));
        } catch (err) {
            console.error('获取配置失败:', err);
            setError('获取配置失败，请稍后再试。');
        } finally {
            setLoading(false);
        }
    };

    // 在组件挂载时获取配置
    useEffect(() => {
        fetchUserConfig();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 处理表单提交
    const onFinish = async () => {
        setSaving(true);
        setError(null);
        try {
            const values = await form.validateFields();
            const payload = {
                qzq_type: values.selectedItems.join(','),
                ...values,
                kjnd: values.kjnd ? values.kjnd.format('YYYY') : null,
            };
            // 发送POST请求到 /rpa/config-update
            const response = await request.post('/rpa/config/update', payload);
            // 根据后端返回的状态处理
            if (response.status === 200) {
                message.success('保存成功！');
                // 可选择重新获取配置以确保最新状态
                fetchUserConfig();
            } else {
                message.error('保存失败，请稍后再试。');
            }
        } catch (err) {
            console.error('保存配置失败:', err);
            setError('保存配置失败，请稍后再试。');
        } finally {
            setSaving(false);
        }
    };

    // 处理表单重置
    const onReset = () => {
        if (config) {
            form.setFieldsValue({
                dwbh: config.dwbh,
                login_way: config.login_way,
                smw_net: config.smw_net,
                nw_net: config.nw_net,
                gscloud_username: config.gscloud_username,
                gscloud_password: config.gscloud_password,
            });
        }
    };

    const backgroundStyle = {
        backgroundImage: `url(${backgroundImage})`,
        backgroundSize: 'cover', // 使背景图片覆盖整个容器
        backgroundPosition: 'center', // 背景图片居中
        backgroundRepeat: 'no-repeat', // 防止背景图片重复
        minHeight: '100vh', // 确保背景图片覆盖整个视口高度
        // 其他您需要的样式
    };

    const handleChange = (newValue) => {
        Modal.confirm({
        title: '确认更改数据库类型？',
        content: `数据库将切换为 ${newValue}，是否确认更改？`,
        onOk() {
            setDatabasetype(newValue);
            request.get('/execute/initsql?databasetype='+newValue);
            window.location.reload();
        },
        okText: '确认',
        onCancel() {
            message.info('已取消更改');
        },
        cancelText: '取消',
        });
    };

    return (
        <Row justify="center">
            <Col xs={24} sm={20} md={24} lg={24}>
                <div className="config-page-layout float-center" style={backgroundStyle}>
                    <Title level={2}>
                    用户配置
                    <Space className='float-right' style={{ marginLeft: 8 }} hidden={config.showdatabasetype==='0'}>
                        <Title level={4}>数据库类型：</Title>
                        <Select
                            className='float-right'
                            value={databasetype}
                            onChange={(value) => handleChange(value)}
                        >
                            {databaselist.map((type) => (
                                <Option key={type} value={type}>
                                    {type}
                                </Option>
                            ))}
                        </Select>
                    </Space>
                    </Title>
                    {error && <Alert message={error} type="error" showIcon style={{marginBottom: 16}}/>}
                    <Spin spinning={loading}>
                        <Form
                            form={form}
                            layout="vertical"
                            onFinish={onFinish}
                            initialValues={{
                                selectedItems: initialSelected,
                            }}
                        >
                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 单位编号 */}
                                    <Form.Item
                                        label="单位编号"
                                        name="dwbh"
                                        rules={[{required: true, message: '请输入单位编号!'}]}
                                    >
                                        <Input placeholder="请输入单位编号"/>
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={12}>

                                    {/* 单位ID */}
                                    <Form.Item
                                        label="单位ID"
                                        name="dwid"
                                        rules={[{required: true, message: '请输入单位ID!'}]}
                                    >
                                        <Input placeholder="请输入单位ID"/>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 单位名称 */}
                                    <Form.Item
                                        label="单位名称"
                                        name="dwmc"
                                        rules={[{required: true, message: '请输入单位名称!'}]}
                                    >
                                        <Input placeholder="请输入单位名称"/>
                                    </Form.Item>

                                </Col>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 账簿 */}
                                    <Form.Item
                                        label="账簿"
                                        name="ledger"
                                        rules={[{required: true, message: '请输入账簿!'}]}
                                    >
                                        <Input placeholder="请输入账簿"/>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 账簿编号 */}
                                    <Form.Item
                                        label="账簿编号"
                                        name="zbbh"
                                        rules={[{required: true, message: '请输入账簿编号!'}]}
                                    >
                                        <Input placeholder="请输入账簿编号"/>
                                    </Form.Item>

                                </Col>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 科目体系 */}
                                    <Form.Item
                                        label="科目体系"
                                        name="kmtx"
                                        rules={[{required: true, message: '请输入科目体系!'}]}
                                    >
                                        <Input placeholder="请输入科目体系"/>
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 科目体系ID */}
                                    <Form.Item
                                        label="科目体系ID"
                                        name="kmtx_id"
                                        rules={[{required: true, message: '请输入科目体系ID!'}]}
                                    >
                                        <Input placeholder="请输入科目体系ID"/>
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 会计年度 */}
                                    <Form.Item
                                        label="默认会计年度"
                                        name="kjnd"
                                        rules={[{required: true, message: '请选择默认会计年度!'}]}
                                    >
                                        <DatePicker
                                            picker="year"
                                            style={{ width: '100%' }}
                                        />
                                    </Form.Item>

                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={8} md={8}>
                                    {/* 模型 */}
                                    <Form.Item
                                        label="模型"
                                        name="model"
                                        rules={[{required: true, message: '请输入模型!'}]}
                                    >
                                        <Input placeholder="请输入模型"/>
                                    </Form.Item>

                                </Col>
                                <Col xs={24} sm={8} md={8}>
                                    <Form.Item
                                        label="报表配置选择"
                                        name="selectedItems"
                                        rules={[{required: true, message: "请选择至少一个选项！"}]}
                                    >
                                        <Select
                                            mode="multiple"
                                            placeholder={loading ? "加载中..." : "请选择选项"}
                                            loading={loading}
                                            allowClear
                                            style={{width: "100%"}}
                                        >
                                            {typeList.map((type) => (
                                                <Option key={type} value={type}>
                                                    {type}
                                                </Option>
                                            ))}
                                        </Select>
                                    </Form.Item>

                                </Col>
                                <Col xs={24} sm={8} md={8}>
                                    <Form.Item
                                        label="报表是否包含行列描述"
                                        name="need_report_desc"
                                        rules={[{required: true, message: "请选择至少一个选项！"}]}
                                    >
                                        <Select
                                            // mode="multiple"
                                            loading={loading}
                                            allowClear
                                            style={{width: "100%"}}
                                        >
                                                <Option key='是' value='是'>是</Option>
                                                <Option key='否' value='否'>否</Option>
                                        </Select>
                                    </Form.Item>

                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={12}>
                                    {/* 登录方式选择 */}
                                    <Form.Item
                                        label="登录方式"
                                        name="login_way"
                                        rules={[{required: true, message: '请选择登录方式!'}]}
                                    >
                                        <Select placeholder="请选择登录方式">
                                            {modelist.map((mode) => (
                                                <Option key={mode} value={mode}>
                                                    {mode}
                                                </Option>
                                            ))}
                                        </Select>
                                    </Form.Item>

                                </Col>
                                <Col xs={24} sm={12} md={12}>
                                    {/* GSCloud 配置 */}
                                    <Form.Item
                                        shouldUpdate={(prevValues, currentValues) => prevValues.login_way !== currentValues.login_way}>
                                        {({getFieldValue}) =>
                                            getFieldValue('login_way') === '账号密码登录' ?
                                                <Form.Item
                                                    label="GSCloud 网址"
                                                    name="smw_net"
                                                    rules={[{required: true, message: '请输入 GSCloud 网址!'}, {
                                                        type: 'url',
                                                        message: '请输入有效的网址!'
                                                    }]}
                                                >
                                                    <Input placeholder="请输入 GSCloud 网址"/>
                                                </Form.Item> :
                                                <Form.Item
                                                    label="GSCloud 网址"
                                                    name="nw_net"
                                                    rules={[{required: true, message: '请输入 GSCloud 网址!'}, {
                                                        type: 'url',
                                                        message: '请输入有效的网址!'
                                                    }]}
                                                >
                                                    <Input placeholder="请输入 GSCloud 网址"/>
                                                </Form.Item>
                                        }
                                    </Form.Item>

                                </Col>
                            </Row>

                            <Row gutter={16}>
                                <Col xs={24} sm={12} md={24}>
                                    <Form.Item
                                        shouldUpdate={(prevValues, currentValues) => prevValues.login_way !== currentValues.login_way}>
                                        {({getFieldValue}) =>
                                            getFieldValue('login_way') === '账号密码登录' ?
                                                <>
                                                    <Form.Item
                                                        label="GSCloud 用户名"
                                                        name="gscloud_username"
                                                        rules={[{required: true, message: '请输入 GSCloud 用户名!'}]}
                                                    >
                                                        <Input placeholder="请输入 GSCloud 用户名"/>
                                                    </Form.Item>
                                                    <Form.Item
                                                        label="GSCloud 密码"
                                                        name="gscloud_password"
                                                        rules={[{required: true, message: '请输入 GSCloud 密码!'}]}
                                                    >
                                                        <Input.Password placeholder="请输入 GSCloud 密码"/>
                                                    </Form.Item>
                                                </> : null
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            {/* 保存和重置按钮 */}
                            <Form.Item>
                                <Space>
                                    <Button type="primary" htmlType="submit" loading={saving}>
                                        保存
                                    </Button>
                                    <Button htmlType="button" onClick={onReset}>
                                        重置
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Spin>
                </div>
            </Col>
        </Row>
    );
};

export default UserConfig;
